package com.borqsprocessmanager.receiver;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.PowerManager;
import android.util.Log;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.BatteryManagerService;
import com.borqsprocessmanager.ConfigParams;
import com.borqsprocessmanager.Constant;
import com.borqsprocessmanager.MainActivity;
import com.borqsprocessmanager.R;
import com.borqsprocessmanager.BatteryManagerService.IStateReceiver;
import com.borqsprocessmanager.interfaces.IReciverCallback;
import com.borqsprocessmanager.util.CPUFreqSetting;
import com.borqsprocessmanager.util.PreferencesUtil;

/*
 * IntentFilter filter = new IntentFilter();
 * filter.addAction(Intent.ACTION_SCREEN_ON);
 * filter.addAction(Intent.ACTION_SCREEN_OFF);
 * filter.addAction(Intent.ACTION_BATTERY_CHANGED);
 * mService.registerReceiver(this, filter);
 */
public class ScreenAndConChangedReceiver extends BaseBroadcastReceiver
        implements IStateReceiver {
    private final String TAG = "ScreenChangedReceiver";

    private Timer timer;
    private BatteryManagerService mService = null;
    private PowerManager pm;

    private boolean isScreenOn;
    private boolean isSreenOpened;
    private boolean isConnected;
    private boolean actionTimeTask;

    private long screenOnTime;

    public ScreenAndConChangedReceiver(BatteryManagerService service) {
        mService = service;
        pm = (PowerManager) App.mContext
                .getSystemService(Context.POWER_SERVICE);
        // sampleIsScreenOnChanged(true);
        isScreenOn = true;
        isSreenOpened = true;
        isConnected = false;
        actionTimeTask = false;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.v(TAG, "action===" + action);
        if (action.equals(Intent.ACTION_SCREEN_ON)) {
            // isScreenOn = true;

            sampleIsScreenOnChanged(true);
            isSreenOpened = true;
            onScreenOn();
            screenOnTime = System.currentTimeMillis();
            recoverCpu();
            boolean newData = PreferencesUtil.getInstance(context).getBoolean(
                    Constant.KEY_IS_NEWDATA);
            com.borqsprocessmanager.util.Log.v(TAG, "newData===" + newData);
            if (newData) {
                showNotifacation(context);
            }
            Log.v(TAG, "ACTION_SCREEN_ON===" + isScreenOn);
        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
            // isScreenOn = false;
            sampleIsScreenOnChanged(false);
            isSreenOpened = true;
            onScreenOff(screenOnTime, System.currentTimeMillis());
            Log.v(TAG, "ACTION_SCREEN_OFF===" + isScreenOn);
        } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
            isConnected = true;
            Log.v(TAG, "BatteryManagerService.isConnected===true");
        } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            isConnected = false;
            Log.v(TAG, "BatteryManagerService.isConnected===false");
        }
    }

    private void recoverCpu() {
        PreferencesUtil util = PreferencesUtil.getInstance(App.mContext);
        if (util.getBoolean(Constant.KAY_ISCPU_FREP_STATE)) {
            CPUFreqSetting cpufreqSetting = new CPUFreqSetting();
            cpufreqSetting.setUserSpaceMod(CPUFreqSetting.TAG_ONDEMAND);
            util.putBoolean(Constant.KAY_ISCPU_FREP_STATE, false);
        }
    }

    private void showNotifacation(Context context) {
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        // 点击通知时转移内容
        Intent intent = new Intent(context, MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification notification = new Notification();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // 设置通知在状态栏显示的图标
        notification.icon = R.drawable.icon;
        // 当我们点击通知时显示的内容
        // notification.tickerText = "检测到异常耗电应用";

        // 通知时发出的默认声音
        // notification.defaults = Notification.DEFAULT_SOUND;

        // 设置通知显示的参数
        notification.setLatestEventInfo(context,
                context.getString(R.string.app_name),
                context.getString(R.string.notification), pendingIntent);

        // 这个可以理解为开始执行这个通知
        com.borqsprocessmanager.util.Log.v(TAG, "notificationManager");
        notificationManager.notify(0, notification);
    }

    private void onScreenOff(long onTime, long offTime) {
        if ((offTime - onTime) > ConfigParams.SREEN_ON_BASE_LINE) {
            if (!actionTimeTask) {
                actionTimeTask = true;
                com.borqsprocessmanager.util.Log.v(TAG,
                        " ConfigParams.SREEN_OFF_WORKING_TIME===if"
                                + ConfigParams.SREEN_OFF_WORKING_TIME);
                TimerTask task = new closeProcessTimerTask();
                timer = new Timer();
                timer.schedule(task, ConfigParams.SREEN_OFF_WORKING_TIME);
            } else {
                com.borqsprocessmanager.util.Log.v(TAG,
                        " ConfigParams.SREEN_OFF_WORKING_TIME===else");
                timer.cancel();
                TimerTask task = new closeProcessTimerTask();
                timer = new Timer();
                timer.schedule(task, ConfigParams.SREEN_OFF_WORKING_TIME);
            }
        }
    }

    private void onScreenOn() {
        if (actionTimeTask) {
            actionTimeTask = false;
            timer.cancel();
        }
    }

    @Override
    public boolean getState() {
        com.borqsprocessmanager.util.Log.v(TAG, "getState_isScreenOn==="
                + isScreenOn);
        com.borqsprocessmanager.util.Log.v(TAG, "getState_isSreenOpened==="
                + isSreenOpened);
        com.borqsprocessmanager.util.Log.v(TAG, "getState_isConnected==="
                + isConnected);

        return !pm.isScreenOn() && !isSreenOpened && !isConnected;
    }

    @Override
    public void initState() {
        isSreenOpened = false;
    }

    class closeProcessTimerTask extends TimerTask {
        /**
         * 此计时器任务要执行的操作。
         */
        public void run() {
            if (actionTimeTask) {
                Log.v(TAG, "TestTimerTask.exc");
                if (mIReciverCallback != null) {
                    mIReciverCallback
                            .executeCallback(IReciverCallback.TYPE_SCREEN);
                }
            }
        }
    }

    private void sampleIsScreenOnChanged(boolean b) {
        this.isScreenOn = b;
        com.borqsprocessmanager.util.Log.v(TAG, "sampleIsScreenOnChanged==="
                + isScreenOn);
    }
}
